/*
 * Copyright 2012 Honestyworks Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package jp.honestyworks.pbcache;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.appengine.api.utils.SystemProperty;
import com.google.apphosting.api.ApiProxy;

/**
 * cache context creation.
 * 
 * @author miztaka
 *
 */
public class ContextFilter implements Filter {
	
	private static final Log logger = LogFactory.getLog(ContextFilter.class);
    
    static {
    	// enable cache only in production environment
        if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
            logger.info("setup ApiProxy.");
            ApiProxyHook hook = new ApiProxyHook(ApiProxy.getDelegate());
            hook.getHooks().put("datastore_v3", new DatastoreCacheProxyHook(hook.getBaseDelegate()));
            ApiProxy.setDelegate(hook);
        }
    }
    
    public ContextFilter() {
    	super();
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
        return;
    }
  
    public void doFilter(ServletRequest request, ServletResponse response, 
    		FilterChain chain) throws IOException, ServletException {
    	
    	chain.doFilter(request, response);
    	
    	// after that, reset local cache.
    	CacheContext.getInstance().getCacheService().resetLocalCache();
    }

	public void destroy() {
		
	}
}
